<?php
class CatalogModel extends ModelBase
{
	private static $_tableName = 'catalog';
	
	public static $types = array(
		'channel'	=> '频道',
		'list'		=> '列表页',
		'info'		=> '信息简介'
	);
	
	public static function add($name, $pid=0, $type='list', $memo='', $priority=100, $tpl='')
	{
		if (empty($name)){
			return false;
		}
		$data = array(
			'name'	=> $name,
			'pid'	=> $pid,
			'type'	=> $type,
			'memo'	=> $memo,
			'tpl'	=> $tpl,
			'priority' => $priority
		);
		return self::queryInsert(self::$_tableName, $data);
	}
	
	public static function update($cid, $data)
	{
		return self::queryUpdate(self::$_tableName, $data, "id={$cid}");
	}
	
	public static function get($cid)
	{
		$data = self::querySelectSingle(self::$_tableName, array('*'), "id={$cid}");
		if ($data) {
			if ($data['type']=='channel'){
				$data['url'] = '/channel/' . $data['id'] . '.html';
			}elseif ($data['type']=='list'){
				$data['url'] = '/list/' . $data['id'] . '.html';
			}elseif ($data['type']=='info'){
				$data['url'] = '/info/' . $data['id'] . '.html';
			}
		}
		return $data;
	}
	
	public static function delete($cid)
	{
		return self::queryDelete(self::$_tableName, "id={$cid}");
	}
	
	public static function getList($pid=0)
	{
		$data = self::querySelect(self::$_tableName, array('*'), '1');
		$tree = array();
		self::_mkTree($data, $pid, 0, $tree);
		foreach ($tree as &$item){
			if ($item['type']=='channel'){
				$item['url'] = '/channel/' . $item['id'] . '.html';
			}elseif ($item['type']=='list'){
				$item['url'] = '/list/' . $item['id'] . '.html';
			}elseif ($item['type']=='info'){
				$item['url'] = '/info/' . $item['id'] . '.html';
			}
		}
		return $tree;
	}
	
	public static function _mkTree($data, $pid, $level, &$tree)
	{
		++$level;
		foreach ($data as $key=>$item) {
			if ($item['pid']==$pid){
				$item['level'] = $level;
				$tree[] = $item;
				unset($data[$key]);
				self::_mkTree($data, $item['id'], $level, $tree);
			}
		}
	}
}